package com.jbm.jbmsupplier.zp.presenters;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.jbm.core.iface.IFileObject;
import com.jbm.jbmsupplier.net.NetinterSend;
import com.jbm.jbmsupplier.shared.SharedPreferActivity;
import com.jbm.jbmsupplier.zp.FactouryActivity.ChatSaveMessage;
import com.jbm.jbmsupplier.zp.FactouryActivity.FacturyActivity;
import com.jbm.jbmsupplier.zp.entity.Buddy_ListData;
import com.jbm.jbmsupplier.zp.entity.ChatMsgEntity;
import com.jbm.jbmsupplier.zp.models.MyServiceInterface;
import com.jbm.jbmsupplier.zp.sqldata.MySqliteUtlis;
import com.jbm.jbmsupplier.zp.utils.ClassUser;
import com.jbm.jbmsupplier.zp.utils.DataFormate;
import com.jbm.jbmsupplier.zp.views.MyServiceView;
import com.jbm.onehome.common.OHInterface;
import com.jbm.onehome.iface.CallGroupEntity;
import com.jbm.onehome.iface.ContactEntity;
import com.jbm.onehome.iface.LoginEntity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import static com.jbm.jbmsupplier.zp.utils.ClassUser.getDate;
import static com.jbm.jbmsupplier.zp.utils.TableName.BUDDY;
import static com.jbm.jbmsupplier.zp.utils.TableName.CHAT;
import static com.jbm.jbmsupplier.zp.utils.TableName.CHATGROUD;
import static com.jbm.jbmsupplier.zp.utils.TableName.GROUD;
import static com.jbm.jbmsupplier.zp.utils.TableName.RECENT;

/**
 * Created by 家帮忙 on 2017/7/11.
 */

public class MyServices implements MyServiceInterface{
    private Context context;
    private MyServiceView myServiceView;
    private  boolean boo=false;//控子服务第一次启动是否链接两次服务器
    private ClassUser ClassUser;
    private FacturyActivity facturyActivity=null;
    private ArrayList<ChatMsgEntity> arrayList;
    private ArrayList<HashMap<String, String>> list1;
    private final int GETDUBY=0001;
    public MyServices(Context context, MyServiceView myServiceView) {
        this.context = context;
        this.myServiceView = myServiceView;
        ClassUser=new ClassUser(context);
    }


    /**
     * 初始化数据
     * 判断init方法只能执行一次连接操作
     *
     * @param tag
     */
    @Override
    public void InitData(int tag) {//初始化数据
        if (tag==1){
            SharedPreferActivity sharedLoginActivity = new SharedPreferActivity(context);
            if(sharedLoginActivity.getBoolearNetConn()==true){
             myServiceView.setUpdata("关机");
                boo=true;
            }
        }else if (tag==2){
            if (boo==false){
                myServiceView.setUpdata("开机");
            }
            boo=false;
        }
        if (facturyActivity==null){
            facturyActivity=new FacturyActivity();
        }
    }

    @Override
    public void NewText(Integer account_id, String text, long timestamp) {
        ChatMsgEntity chatmsg = new ChatMsgEntity();
        chatmsg.setDate(getData(timestamp));
        chatmsg.setTo_id(account_id);
        chatmsg.setFlag(8);
        chatmsg.setTags(0);
        chatmsg.setText(text);
        SaveChatMassage(0,account_id, null,text,chatmsg,"text") ;
        myServiceView.getAllData(chatmsg);
        boo=false;

    }

    @Override
    public void NewFile(Integer account_id, IFileObject fo, long timestamp) {
        ChatMsgEntity chatmsg = new ChatMsgEntity();
        chatmsg.setDate(getData(timestamp));
        chatmsg.setTo_id(account_id);
        chatmsg.setTags(0);
        if (fo.filetype.equals("pic")) {
            chatmsg.setFlag(10);
            chatmsg.setRoute(fo.filepath);
            chatmsg.setFiletype(fo.filetype);
            SaveChatMassage(0,account_id, fo,"",chatmsg,"pic") ;
        } else if (fo.filetype.equals("audio")) {
            chatmsg.setMediaName(fo.filepath);
            chatmsg.setFlag(12);
            chatmsg.setFiletype(fo.filetype);

            SaveChatMassage(0,account_id, fo,"",chatmsg,"audio") ;
        }
        myServiceView.getAllData(chatmsg);
        boo=false;
    }
    @Override
    public void NewPay(Integer account_id, String msg, BigDecimal fee, String paytype, long timestamp) {
        String payDate = DataFormate.getDateTimeFromMillisecond(DataFormate.StringD, timestamp);
        //四舍五入
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
        String afee1 = df.format(fee);
        ChatMsgEntity chatmsg = new ChatMsgEntity();
        chatmsg.setDate(getData(timestamp));
        chatmsg.setTo_id(account_id);
        chatmsg.setFlag(14);
        chatmsg.setPayDate(payDate);
        chatmsg.setPayMode(paytype);
        chatmsg.setPayMoney(afee1);
        myServiceView.getAllData(chatmsg);
        boo=false;
    }

    @Override
    public void AddContact(ContactEntity ce) {
        list1 = MySqliteUtlis.GetInstan(context).showalldata(BUDDY,ce.getLoginId());
        if (list1 == null) {
            MySqliteUtlis.GetInstan(context).StoringBuddydata(BUDDY , ce.getLoginId(),ce.getNickname(),ce.getAccount(),ce.getMobile(),"",ce.getLogo(),"","","",1,ClassUser.getLogin());
        }else{
            if (list1.contains(ce.getLoginId())){
                if (MySqliteUtlis.GetInstan(context).showFriendsToID(BUDDY,ce.getLoginId(),ClassUser.getLogin()).getIsfriends() == 0){
                    MySqliteUtlis.GetInstan(context).UpdateIsfriends(BUDDY ,ce.getLoginId());
                }
            }else {
                MySqliteUtlis.GetInstan(context).StoringBuddydata(BUDDY, ce.getLoginId(),ce.getNickname(),ce.getAccount(),ce.getMobile(),"",ce.getLogo(),"","","",1, ClassUser.getLogin());
            }
        }
        setSendBroad();//添加好友
        boo=false;
    }

    @Override
    public void DropContact(ContactEntity ce) {
        try {
                MySqliteUtlis.GetInstan(context).deletedata(RECENT, String.valueOf(ce.getLoginId()),ClassUser.getLogin());
                MySqliteUtlis.GetInstan(context).deletedata(BUDDY, String.valueOf(ce.getLoginId()),ClassUser.getLogin());
        }catch (Exception e){
            e.fillInStackTrace();
        }
        setSendBroad();//删除好友
        boo=false;
    }
    private void setSendBroad(){
        Intent intent = new Intent();
        intent.putExtra("messageFlag",50);
        intent.setAction("AddContact");
        context.sendBroadcast(intent);

    }

    /**
     * 接收群消息分别是什么类型
     * tag  代表标识
     * 8 接收文本消息
     * 10 接收图片
     * 12 接收语音
     * 14 接收支付 //暂时未使用
     * @param arrayList
     * @param tag
     */

    @Override
    public void SaveData(ArrayList<ChatMsgEntity> arrayList,int tag) {
        this.arrayList=arrayList;
        if (tag==8){
            handler.sendMessage(handler.obtainMessage(8,arrayList));
        }else if(tag==10){
            handler.sendMessage(handler.obtainMessage(10,arrayList));
        } else  if (tag==12){
            handler.sendMessage(handler.obtainMessage(12,arrayList));
        }else  if (tag==14){
            handler.sendMessage(handler.obtainMessage(14,arrayList));
        }
}

    /**
     * 获取到群文本消息
     *  将文本消息ChatMsgEntity传入myServiceView.getAllData(chatmsg);方法
     *  放到一个集合中
     * @param cg_id
     * @param account_id
     * @param text
     * @param timestamp
     */


    @Override
    public void CGNewText(int cg_id, Integer account_id, String text, long timestamp) {
            ChatMsgEntity chatmsg = new ChatMsgEntity();
            chatmsg.setDate(getData(timestamp));
            chatmsg.setTo_id(account_id);
            chatmsg.setFlag(8);
            chatmsg.setCgid(cg_id);
            chatmsg.setText(text);
            chatmsg.setTags(1);
        SaveChatMassage(cg_id,account_id, null,text,chatmsg,"grotext") ;

        myServiceView.getAllData(chatmsg);
            boo = false;



    }
    /**
     * 获取到群文本消息
     *  将文件消息ChatMsgEntity传入myServiceView.getAllData(chatmsg);方法
     *  放到一个集合中
     * @param cg_id
     * @param account_id
     * @param fo
     * @param timestamp
     */

    @Override
    public void CGNewFile(int cg_id, Integer account_id, IFileObject fo, long timestamp) {
        ChatMsgEntity chatmsg = new ChatMsgEntity();
        chatmsg.setDate(getData(timestamp));
        chatmsg.setTo_id(account_id);
        chatmsg.setCgid(cg_id);
        chatmsg.setTags(1);
         if (fo.filetype.equals("pic")) {
            chatmsg.setFlag(10);
            chatmsg.setRoute(fo.filepath);
            chatmsg.setFiletype(fo.filetype);
             SaveChatMassage(cg_id,account_id, fo,"",chatmsg,"gropic") ;
         } else if (fo.filetype.equals("audio")) {
            chatmsg.setMediaName(fo.filepath);
            chatmsg.setFlag(12);
            chatmsg.setFiletype(fo.filetype);
             SaveChatMassage(cg_id,account_id, fo,"",chatmsg,"groaudio") ;
         }
        myServiceView.getAllData(chatmsg);
        boo=false;
    }

    /**
     * 如果有新订单就会创建一个新群
     * @param cg
     */
    @Override
    public void addToUnit(CallGroupEntity cg) {
     //群组表
        MySqliteUtlis.GetInstan(context).InsertGroad(GROUD,"群组名"+cg.getCgId()+"创建人"+ClassUser.getLogin(),"1",getDate()+"","群消息",0,cg.getCgId(),1,ClassUser.getLogin());
        sendBroad();
    }

    /**
     * 保存好友和群的聊天记录
     * @param cg_id
     * @param account_id
     * @param fo
     * @param text
     * @param chatmsg
     * @param tagname
     */
    @Override
    public void SaveChatMassage(int cg_id,Integer account_id, IFileObject fo,String text, ChatMsgEntity chatmsg, String tagname) {
        Buddy_ListData namse = MySqliteUtlis.GetInstan(context).showFriendsToID(BUDDY, account_id, ClassUser.getLogin());
        NetinterSend netinterSend=new NetinterSend(handler);
        switch (tagname) {
            case "text":
                if (namse == null) {
                    netinterSend.getUerMessage(account_id,GETDUBY);
                    MySqliteUtlis.GetInstan(context).StoringChatData(CHAT, account_id, OHInterface.getG_server().logo, arrayList.get(0).getText(), chatmsg.getDate(), "", "", "", "", "", "", "", "", "", "", 8, 0, "true", ClassUser.getLogin());
                } else {
                    MySqliteUtlis.GetInstan(context).StoringChatData(CHAT, account_id, OHInterface.getG_server().logo, text, chatmsg.getDate(), namse.getNickname(), "", "", "", "", "", "", "", "", "", 8, 0, "true", ClassUser.getLogin());
                }
                break;
            case "pic":
                if (namse == null) {
                    netinterSend.getUerMessage(account_id,GETDUBY);
                    MySqliteUtlis.GetInstan(context).StoringChatData(CHAT, account_id, OHInterface.getG_server().logo, "", chatmsg.getDate(), "", fo.filepath, "", "", "", "", "", "", "", "", 10, 0, "true", ClassUser.getLogin());
                } else {
                    MySqliteUtlis.GetInstan(context).StoringChatData(CHAT, account_id, OHInterface.getG_server().logo, "", chatmsg.getDate(), namse.getNickname(), fo.filepath, "", "", "", "", "", "", "", "", 10, 0, "true", ClassUser.getLogin());
                }
                break;
            case "audio":
                if (namse == null) {
                     netinterSend.getUerMessage(account_id,GETDUBY);
                    MySqliteUtlis.GetInstan(context).StoringChatData(CHAT, account_id, OHInterface.getG_server().logo, "", chatmsg.getDate(), "", "", fo.filepath, "", "", "", "", "", "", "", 12, 0, "true", ClassUser.getLogin());
                } else {
                    MySqliteUtlis.GetInstan(context).StoringChatData(CHAT, account_id, OHInterface.getG_server().logo, "", chatmsg.getDate(), namse.getNickname(), "", fo.filepath, "", "", "", "", "", "", "", 12, 0, "true", ClassUser.getLogin());
                }
                break;
            case "grotext":
                MySqliteUtlis.GetInstan(context).InsertGroadTable(CHATGROUD, MySqliteUtlis.GetInstan(context).SelectName(GROUD, cg_id) + "", OHInterface.getG_server().logo, chatmsg.getDate(), text, "", account_id, -1, -1, -0, "", "", "", "", 1, "", "", 8, cg_id, 1, "true", ClassUser.getLogin());
                break;
            case "gropic":
                MySqliteUtlis.GetInstan(context).InsertGroadTable(CHATGROUD, MySqliteUtlis.GetInstan(context).SelectName(GROUD, cg_id) + "", OHInterface.getG_server().logo, chatmsg.getDate(), "", "", account_id, -1, -1, -0, "", fo.filepath, "", "", 1, "", "", 10, cg_id, 1, "true", ClassUser.getLogin());

                break;
            case "groaudio":
                MySqliteUtlis.GetInstan(context).InsertGroadTable(CHATGROUD, MySqliteUtlis.GetInstan(context).SelectName(GROUD, cg_id) + "", OHInterface.getG_server().logo, chatmsg.getDate(), "", "", account_id, -1, -1, -0, "", "", fo.filepath, "", 1, "", "", 12, cg_id, 1, "true", ClassUser.getLogin());
                break;

        }
        if (chatmsg.getTags() != 1)
        {
        ArrayList<String> als = MySqliteUtlis.GetInstan(context).showaRecentContactsid(RECENT, account_id, ClassUser.getLogin());
        if (!als.toString().contains(account_id + "")) {
            MySqliteUtlis.GetInstan(context).StoringRecentID(RECENT, account_id, ClassUser.getLogin(), chatmsg.getDate());
        } else if (als.toString() == null) {
            MySqliteUtlis.GetInstan(context).StoringRecentID(RECENT, account_id, ClassUser.getLogin(), chatmsg.getDate());
        }
    }











    }


    /**
     * 发送广播 将更新消息页面的数据
     */
    public void sendBroad(){
        Intent intent = new Intent();
        intent.putExtra("messageFlag", 50);
        intent.setAction("MSG");
        context.sendBroadcast(intent);
    }
    private String getData(long timestam){
        return   DataFormate.getDateTimeFromMillisecond(DataFormate.StringF, timestam);//1496368282634
    }

    /**
     * 使用的是工厂模式
     * 将    ArrayList<ChatMsgEntity> 的数据传给想对应的类
     * 每个类都有一个统一方法接口setDataChat();
     */
    Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case 8:
                ArrayList<ChatMsgEntity>  arrlist=(ArrayList<ChatMsgEntity> )msg.obj;
             if (arrlist.size()>=1){
                 ChatSaveMessage fatext = facturyActivity.setAllData(8);//保存文本消息
                 fatext.setDataChat(context,arrlist,ClassUser);
             }
                break;
            case 10:
                ArrayList<ChatMsgEntity>  arrlist1=(ArrayList<ChatMsgEntity> )msg.obj;
                if (arrlist1.size()>=1){
                    ChatSaveMessage file = facturyActivity.setAllData(10);//保存图片
                    file.setDataChat(context,arrlist1,ClassUser);
                }
                break;
            case 12:
                ArrayList<ChatMsgEntity>  arrlist2=(ArrayList<ChatMsgEntity> )msg.obj;
                if (arrlist2.size()>=1){
                    ChatSaveMessage fileau = facturyActivity.setAllData(12);//保存语音
                    fileau.setDataChat(context,arrayList,ClassUser);
                }
                break;
            case 14:
                ArrayList<ChatMsgEntity>  arrlist3=(ArrayList<ChatMsgEntity> )msg.obj;
                if (arrlist3.size()>1){
                    ChatSaveMessage pay = facturyActivity.setAllData(14);
                    pay.setDataChat(context,arrayList,ClassUser);//保存支付
                }
                break;
            case GETDUBY:
                LoginEntity loginEntity=(LoginEntity)msg.obj;
                if (loginEntity.m_code==200) {
                    MySqliteUtlis.GetInstan(context).StoringBuddydata(BUDDY, loginEntity.getLoginId(), loginEntity.getNickname(), loginEntity.getAccount(), "", "", "", "", "", "", 1, ClassUser.getLogin());
                }

                break;
        }
    }
};

}
